package org.ank.food;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class EatenTodayActivity extends Activity implements Runnable{
	
	private static final int MENU_ITEM_VIEW_VALUES = Menu.FIRST;
	private static final int MENU_ITEM_CLEAR = Menu.FIRST+1;
	private static final int MENU_ITEM_EDIT_PROFILE = Menu.FIRST+2;
	private static final int MENU_ITEM_HELP = Menu.FIRST+3;
	private static final int MENU_ITEM_DELETE = Menu.FIRST;
	public static final String INTENT_EXTRA_NAME = "extra";
	
	
	
	private static final int MESSAGE_WAIT = 0;
	private static final int MESSAGE_READY = 1;
	
	private boolean advisePossible;
	private ProgressBar progressBar;
	private int groupId;
	private TextView title, menuIsEmptyTextView, indicatorView;
	private ListView listView;
	private Button addButton,okButton,getAdviceButton;
	private SimpleCursorAdapter adapter;
	private EatenAdapter eAdapter;
	private AdviceManager adviceManager;
	private Intent intent;
	private AdviceHandler handler;
	
	public void onCreate(Bundle b){
		super.onCreate(b);
		setContentView(R.layout.eaten_today_activity);
		
		setTitle(
				getString(R.string.app_name)+" - "+getString(R.string.title_profile)+": "+
				ProfileManager.getInstance(getApplicationContext()).getCurrentProfileName()
				);
		
		Intent parentIntent = getIntent(); 
        if(parentIntent.getIntExtra(ProfileChooseActivity.INTENT_EXTRA_NAME, -1)
        		== ProfileChooseActivity.CALLER_VIEW_PROFILE)
        	Toast.makeText(getApplicationContext(), R.string.toast_profile_saved,
					Toast.LENGTH_SHORT).show();
//		Intent intent = getIntent();
		title = (TextView)findViewById(R.id.eaten_today_title);
		progressBar = (ProgressBar)findViewById(R.id.eaten_today_progressbar);
        indicatorView = (TextView)findViewById(R.id.eaten_today_indicator);
		menuIsEmptyTextView = (TextView)findViewById(R.id.eaten_today_menu_is_empty_textview);
//		title.setText(ProfileManager.getInstance(getApplicationContext()).getCurrentProfileName()+
//				", "+getString(R.string.eng_eaten_today_activity_what_have_you_eaten_today_text));
		listView = (ListView)findViewById(R.id.eaten_today_list);
//		//Log.v("eatentoday", "setting adapter");
		adviceManager = AdviceManager.getInstance(getApplicationContext());
		Intent intent = getIntent();
		
		handler = new AdviceHandler();
		
		if( (groupId = intent.getIntExtra(INTENT_EXTRA_NAME, -1)) != -1){ 
			//if advice is asked (then intent extra contains the group id of desirable product)
			
			Thread t = new Thread(this);
			t.start();
//			if( !adviceManager.makeAndSaveSingleAdvice(groupId) ){
//				AlertDialog.Builder builder = new AlertDialog.Builder(EatenTodayActivity.this);
//				builder.setMessage(getString(R.string.eaten_today_alert_message));
//				builder.setNegativeButton(R.string.eaten_today_alert_try_another, 
//						new DialogInterface.OnClickListener(){
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//								Intent intent = new Intent();
//					    		intent.setClass(getApplicationContext(), ConfirmExperienceActivity.class);
//					    		intent.putExtra(ConfirmExperienceActivity.INTENT_EXTRA_NAME_MODE, 
//					    					ConfirmExperienceActivity.SHOW_GROUPS_FOR_ADVICE_MODE);
//					    		startActivity(intent);
//					    		finish();
//							}
//						});
//				builder.setPositiveButton(R.string.eaten_today_alert_show_values, 
//						new DialogInterface.OnClickListener(){
//						@Override
//						public void onClick(DialogInterface dialog,	int which) {
//							Intent intent = new Intent();
//				    		intent.setClass(getApplicationContext(), MenuValuesActivity.class);
//				    		startActivity(intent);
//				    		finish();
//						}
//					});
//				builder.setNeutralButton(R.string.eaten_today_alert_back_to_menu, 
//						new DialogInterface.OnClickListener(){
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//							}
//						});
////				builder.setTitle(R.string.profile_create_alert_dialog_title);
//				builder.show();
//			}
			
		}
		Cursor cursor = adviceManager.getEaten();
		cursor.moveToFirst();
//		adapter = new SimpleCursorAdapter(getApplicationContext(),
//				android.R.layout.simple_list_item_1,
//				cursor,
//				new String[]{AdviceProvider.COLUMN_NAMES[AdviceProvider.PRODUCT_NAME]},
//				new int[]{android.R.id.text1}
//				);
//		adapter = new SimpleCursorAdapter(getApplicationContext(),
//				android.R.layout.two_line_list_item, cursor,
//				new String[]{
//					AdviceProvider.COLUMN_NAMES[AdviceProvider.PRODUCT_NAME],
//					AdviceProvider.COLUMN_NAMES[AdviceProvider.WEIGHT_ITEM_NAME]
//				},
//				new int[]{android.R.id.text1, android.R.id.text2}
//				);
		eAdapter = new EatenAdapter(getApplicationContext(),
				android.R.layout.two_line_list_item, cursor,
				new String[]{
					AdviceProvider.COLUMN_NAMES[AdviceProvider.PRODUCT_NAME],
					AdviceProvider.COLUMN_NAMES[AdviceProvider.WEIGHT_ITEM_NAME]
				},
				new int[]{android.R.id.text1, android.R.id.text2}
				);
		listView.setAdapter(eAdapter);
		
		if(/*adapter.getCount()*/eAdapter.getCount() > 0)
			menuIsEmptyTextView.setVisibility(TextView.INVISIBLE);
		addButton = (Button)findViewById(R.id.eaten_today_add_button);
		addButton.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
        		intent.setClass(getApplicationContext(), ConfirmExperienceActivity.class);
        		startActivity(intent);
        		finish();
			}
		});
		getAdviceButton = (Button)findViewById(R.id.eaten_today_get_advice_button);
		getAdviceButton.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				if(exceeded()){
					AlertDialog.Builder builder = new AlertDialog.Builder(EatenTodayActivity.this);
					builder.setMessage(getString(R.string.eaten_today_cant_get_advice));
					builder.setPositiveButton(R.string.eaten_today_alert_show_values, 
							new DialogInterface.OnClickListener(){
							@Override
							public void onClick(DialogInterface dialog,	int which) {
								Intent intent = new Intent();
					    		intent.setClass(getApplicationContext(), MenuValuesActivity.class);
					    		startActivity(intent);
					    		finish();
							}
						});
					builder.setNegativeButton(R.string.eaten_today_alert_back_to_menu, 
							new DialogInterface.OnClickListener(){
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							});
					builder.show();
				}else{
					Intent intent = new Intent();
					intent.setClass(getApplicationContext(), ConfirmExperienceActivity.class);
					intent.putExtra(ConfirmExperienceActivity.INTENT_EXTRA_NAME_MODE, 
	    					ConfirmExperienceActivity.SHOW_GROUPS_FOR_ADVICE_MODE);
					startActivity(intent);
					finish();
				}
				
//				listView.setAdapter(null);
//				adviceManager.clearEaten();
			}
		});
//		okButton = (Button)findViewById(R.id.eaten_today_ok_button);
//		okButton.setOnClickListener(new Button.OnClickListener(){
//			@Override
//			public void onClick(View v) {
//				Intent intent = new Intent();
////        		intent.setClass(getApplicationContext(), AdviceTodayActivity.class);
//        		intent.setClass(getApplicationContext(), LastAdviceActivity.class);
//        		intent.putExtra(LastAdviceActivity.ADVICE_EXTRA_NAME,
//        				LastAdviceActivity.NEW_ADVICE);
//        		startActivity(intent);
////        		//Log.v("eaten today","before finish111");
//        		finish();
//			}
//		});
		listView.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
				view.performLongClick();
			}
        });
		listView.setOnCreateContextMenuListener(this);
		
		
		
//		if(cursor.getCount() > 0){
//			cursor.moveToFirst();
//			clearButton.setText(cursor.getString(0));
//		}
//		clearButton.setText(String.valueOf(cursor.getCount()));

	}
	
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (ClassCastException e) {
//            //Log.e(TAG, "bad menuInfo", e);
            return;
        }

        Cursor cursor = (Cursor)eAdapter.getItem(info.position);
        if (cursor == null) {
            // For some reason the requested item isn't available, do nothing
            return;
        }
        menu.setHeaderTitle(cursor.getString(0));
		menu.add(0, MENU_ITEM_DELETE, 0, R.string.eaten_today_context_menu_delete);
		
	}
    public boolean onContextItemSelected(MenuItem item){
    	AdapterView.AdapterContextMenuInfo info;
//    	ProfileManager profileManager = ProfileManager.getInstance(getApplicationContext());
        try {
             info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        } catch (ClassCastException e) {
//            //Log.e(TAG, "bad menuInfo", e);
            return false;
        }

        switch (item.getItemId()) {
            case MENU_ITEM_DELETE: 
                adviceManager.deleteEaten((int)info.id);
                eAdapter.changeCursor(adviceManager.getEaten());
                if(eAdapter.getCount() == 0)
                	menuIsEmptyTextView.setVisibility(TextView.VISIBLE);
                return true;
        }
        return false;
    }
    
	public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, MENU_ITEM_VIEW_VALUES, 0, R.string.eaten_today_view_values).
        	setIcon(android.R.drawable.ic_menu_info_details);
        menu.add(0, MENU_ITEM_CLEAR, 0, R.string.eaten_today_clear).
    		setIcon(android.R.drawable.ic_menu_delete);
        menu.add(0, MENU_ITEM_EDIT_PROFILE, 0, R.string.eaten_today_edit_profile).
			setIcon(android.R.drawable.ic_menu_agenda);
        menu.add(0, MENU_ITEM_HELP, 0, R.string.options_menu_help).
			setIcon(android.R.drawable.ic_menu_help);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item) {
//    	Intent intent;
    	
        switch (item.getItemId()) {
        case MENU_ITEM_VIEW_VALUES:
        	intent = new Intent();
    		intent.setClass(getApplicationContext(), MenuValuesActivity.class);
    		intent.putExtra(EnterNameActivity.CALL_FROM_FOLLOWING, false);
    		startActivity(intent);
    		finish();
            return true;
        case MENU_ITEM_CLEAR:
        	if(eAdapter.getCount() == 0)
        		return true; //there are no items in list, nothing to clear and to ask about
        	AlertDialog.Builder builder = new AlertDialog.Builder(EatenTodayActivity.this);
			builder.setMessage(getString(R.string.eaten_today_clear_menu_alert_message));
			builder.setNegativeButton(R.string.warning_no, 
					new DialogInterface.OnClickListener(){
						@Override
						public void onClick(DialogInterface dialog,
								int which) {
						}
					});
			builder.setPositiveButton(R.string.warning_yes, 
					new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface dialog,	int which) {
						listView.setAdapter(null);
						adviceManager.clearEaten();
						menuIsEmptyTextView.setVisibility(TextView.VISIBLE);
					}
				});
			

			builder.create().show();
			return true;
        case MENU_ITEM_EDIT_PROFILE:
        	ProfileManager.getInstance(getApplicationContext()).
        			setProfileMode(ProfileManager.PROFILE_MODE_EDIT);
        	Intent intent = new Intent();
    		intent.setClass(getApplicationContext(), ViewProfileActivity.class);
    		intent.putExtra(ViewProfileActivity.INTENT_EXTRA_NAME, 
    				ViewProfileActivity.CALLER_EATEN_TODAY);
    		startActivity(intent);
    		finish();
    		return true;
        case MENU_ITEM_HELP:
        	intent = new Intent();
        	intent.setClass(getApplicationContext(), InfoActivity.class);
        	startActivity(intent);
        	return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), ProfileChooseActivity.class);
			startActivity(intent);
			finish();
			return true;
		}
	    return super.onKeyDown(keyCode, event);
	}
	
	private class EatenAdapter extends SimpleCursorAdapter{
		
		Cursor cursor;
		AdviceManager am;
		
		public EatenAdapter(Context context, int layout, Cursor c, String[] from, int[] to){
			super(context, layout, c, from, to);
			this.cursor = c;
			this.am = AdviceManager.getInstance(getApplicationContext());
			
		}
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView text1, text2;
			ViewGroup v;
			if (convertView != null)
				v = (ViewGroup)convertView;
			else
				v = (ViewGroup)LayoutInflater.from(getApplicationContext()).
						inflate(R.layout.eaten_list_two_line_item, null);
			text1 = (TextView)v.getChildAt(0);
			text2 = (TextView)v.getChildAt(1);
			int id = getIdByPosition(getCursor(), position);
			text1.setText(am.getEatenItemProductName(id));
			text2.setText(am.getEatenItemAmount(id)+" x "+am.getEatenItemWeightName(id));
			return v;	
		}
		
		private int getIdByPosition(Cursor c, int pos){
			c.moveToPosition(pos);
			return c.getInt(
					c.getColumnIndex( AdviceProvider.COLUMN_NAMES[AdviceProvider.ID] )
				);
		}
	}
	
	@Override
	public void run(){
		Message m;
		m = Message.obtain(handler, MESSAGE_WAIT);
		m.sendToTarget();
		advisePossible = adviceManager.makeAndSaveSingleAdvice(groupId);
		m = Message.obtain(handler, MESSAGE_READY);
		m.sendToTarget();
			
	}
	
	public class AdviceHandler extends Handler{
		
		@Override
		public void handleMessage(Message m){
			switch (m.what){
			
			case MESSAGE_WAIT :
				////Log.v("handler","message wait recived");
				progressBar.setVisibility(View.VISIBLE);
				indicatorView.setVisibility(View.VISIBLE);
				
				break;
			case MESSAGE_READY :
				////Log.v("handler","message ready recived");
				progressBar.setVisibility(View.INVISIBLE);
				indicatorView.setVisibility(View.INVISIBLE);
				if(!advisePossible){
					AlertDialog.Builder builder = new AlertDialog.Builder(EatenTodayActivity.this);
					builder.setMessage(getString(R.string.eaten_today_alert_message));
					builder.setNegativeButton(R.string.eaten_today_alert_try_another, 
							new DialogInterface.OnClickListener(){
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent intent = new Intent();
						    		intent.setClass(getApplicationContext(), ConfirmExperienceActivity.class);
						    		intent.putExtra(ConfirmExperienceActivity.INTENT_EXTRA_NAME_MODE, 
						    					ConfirmExperienceActivity.SHOW_GROUPS_FOR_ADVICE_MODE);
						    		startActivity(intent);
						    		finish();
								}
							});
					builder.setPositiveButton(R.string.eaten_today_alert_show_values, 
							new DialogInterface.OnClickListener(){
							@Override
							public void onClick(DialogInterface dialog,	int which) {
								Intent intent = new Intent();
					    		intent.setClass(getApplicationContext(), MenuValuesActivity.class);
					    		startActivity(intent);
					    		finish();
							}
						});
					builder.setNeutralButton(R.string.eaten_today_alert_back_to_menu, 
							new DialogInterface.OnClickListener(){
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							});

					builder.show();
				}else{
					menuIsEmptyTextView.setVisibility(View.INVISIBLE);
				}
				break;
			
			}
		
		}
	}
	private boolean exceeded(){
		ProfileManager profileManager = ProfileManager.getInstance(getApplicationContext());
		AdviceManager adviceManager = AdviceManager.getInstance(getApplicationContext());
		
		int eatenProtEnergy = adviceManager.getEatenProtEnergy();
		int eatenFatEnergy = adviceManager.getEatenFatEnergy();
		int eatenCarboEnergy = adviceManager.getEatenCarboEnergy();
		
		int protQuota = profileManager.getProtQuota();
		int fatQuota = profileManager.getFatQuota();
		int carboQuota = profileManager.getCarboQuota();
		
		return (eatenProtEnergy >= protQuota ||
				eatenFatEnergy >= fatQuota ||
				eatenCarboEnergy >= carboQuota);
	}
}
